package com.ffad.frame.db.core;


import java.security.SecureRandom;
import java.util.Base64;
import java.util.Properties;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.druid.util.DruidPasswordCallback;
import com.alibaba.druid.util.StringUtils;
import com.ffad.frame.exception.BadPasswordException;

public class DBPasswordCallback extends DruidPasswordCallback {
	private static final Log LOG = LogFactory.getLog(DBPasswordCallback.class);
	private static final long serialVersionUID = 8352871450818066381L;

	// DES加解密key
	private String key = "9588028820109132570743325311898426347857298773549468758875018579537757772163084478873699447306034466200616411960574122434059469100235892702736860872901247123456" ;
	
	@Override
	public void setProperties(Properties properties) {
		super.setProperties(properties);
		String pwd = properties.getProperty("password");
		if (!StringUtils.isEmpty(pwd)) {
			try {
				// 1加密后的密码
				String password = pwd ;
				// 2对密码进行base64解密：得到不可复制使用的二进制文本
				byte[] decode2 = Base64.getDecoder().decode(password.getBytes());
				// 3将二进制文本再通过DES解密得到原始的密码
				byte[] decryResult = decrypt(decode2, key);
				// 4转成char数组
				this.setPassword(new String(decryResult).toCharArray());
				
			} catch (Exception arg3) {
				LOG.error("decrypt password error:", arg3);
				throw new BadPasswordException("decryptFlag password error");
			}
		}

	}
	
	// 解密
	public static byte[] decrypt(byte[] src, String password) throws Exception {
		// DES算法要求有一个可信任的随机数源
		SecureRandom random = new SecureRandom();
		// 创建一个DESKeySpec对象
		DESKeySpec desKey = new DESKeySpec(password.getBytes());
		// 创建一个密匙工厂
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		// 将DESKeySpec对象转换成SecretKey对象
		SecretKey securekey = keyFactory.generateSecret(desKey);
		// Cipher对象实际完成解密操作
		Cipher cipher = Cipher.getInstance("DES");
		// 用密匙初始化Cipher对象
		cipher.init(Cipher.DECRYPT_MODE, securekey, random);
		// 真正开始解密操作
		return cipher.doFinal(src);
	}
		
		
}